<script setup>
import { ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import api from '@/api'
import { Message } from '@arco-design/web-vue'
import OpenLog from '@/components/custom/OpenLog.vue'
import AccountManagement from '@/components/custom/AccountManagement.vue'
import OrderRecord from '@/components/custom/OrderRecord.vue'

const $route = useRoute()
const $router = useRouter()

const id = $route.query.id
const customInfo = ref({})
const productList = ref([])
const readonly = ref(true)
const customFormInfo = ref({})
const popconfirmContent = ref('') // 改变客户状态时的提示文字
const openProductForm = ref({
  custom_id: id,
  start_time: '',
  cycle: '',
  end_time: '',
  clip_num: '',
  product_id: '',
}) // 开通产品表单
const formVisible = ref(false)
const currentActiveKey = ref(0)
const OpenLogRef = ref(null)
const AccountManagementRef = ref(null)
const OrderRecordRef = ref(null)

const getCustomDetails = async () => {
  try {
    const res = await api.get('custom/customDetails/' + id)
    console.log('res', res)
    var customInfo_res = res.data
    customInfo_res.custom_statusText = ''
    switch (customInfo_res.custom_status * 1) {
      case 0:
        customInfo_res.custom_statusText = '意向客户'
        break
      case 1:
        customInfo_res.custom_statusText = '首次使用客户'
        break
      case 2:
        customInfo_res.custom_statusText = '过期客户'
        break
      case 3:
        customInfo_res.custom_statusText = '续费客户'
        break
    }
    customInfo.value = customInfo_res
    customFormInfo.value.id = id
    customFormInfo.value.custom_name = customInfo_res.custom_name
    customFormInfo.value.head_name = customInfo_res.head_name
    customFormInfo.value.mobile = customInfo_res.mobile

    handleChangeTabs(0)
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const getMenuAllList = async () => {
  try {
    const res = await api.get('system/menuAllList')
    console.log('res', res)
    productList.value = res.data
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const updateCustom = async () => {
  if (!customFormInfo.value.custom_name) {
    Message.error('客户名称不可为空')
    return false
  }
  if (!customFormInfo.value.head_name) {
    Message.error('负责人不可为空')
    return false
  }
  if (!customFormInfo.value.mobile) {
    Message.error('电话不可为空')
    return false
  }
  try {
    const res = await api.post('custom/updateCustom', customFormInfo.value)
    Message.success(res.message)
    readonly.value = true
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const cancelUpdateCustom = async () => {
  customFormInfo.value.custom_name = customInfo.value.custom_name
  customFormInfo.value.head_name = customInfo.value.head_name
  customFormInfo.value.mobile = customInfo.value.mobile
  readonly.value = true
}

const handleChangeCustomStatus = async (newValue) => {
  console.log('newValue', newValue)
  if (newValue == 0) {
    popconfirmContent.value = '确定改为关闭状态吗？'
  } else {
    popconfirmContent.value = '确定改为开启状态吗？'
  }
  return false
}

const changeCustomStatus = async () => {
  try {
    const res = await api.get('custom/customStatus/' + id)
    Message.success(res.message)
    getCustomDetails()
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const changeCustomIpStatus = async () => {
  try {
    const res = await api.get('custom/customIpStatus/' + id)
    Message.success(res.message)
    getCustomDetails()
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const getEndTime = async () => {
  var start_time = openProductForm.value.start_time
  var cycle = openProductForm.value.cycle
  if (start_time && cycle) {
    var dd = new Date(openProductForm.value.start_time)
    dd.setDate(dd.getDate() + cycle) //获取n天后的日期
    var y = dd.getFullYear()
    var m = dd.getMonth() + 1
    var d = dd.getDate() < 10 ? '0' + dd.getDate() : dd.getDate()
    var h = dd.getHours() < 10 ? '0' + dd.getHours() : dd.getHours()
    var min = dd.getMinutes() < 10 ? '0' + dd.getMinutes() : dd.getMinutes()
    var s = dd.getSeconds() < 10 ? '0' + dd.getSeconds() : dd.getSeconds()
    let day = y + '-' + m + '-' + d
    openProductForm.value.end_time = day
  }
}

const formSubmit = async () => {
  console.log('openProductForm', openProductForm.value)
  var obj = { ...openProductForm.value }
  obj.product_id = obj.product_id.toString()
  if (!obj.start_time) {
    Message.error('开通日期不可为空')
    return false
  }
  if (!obj.cycle) {
    Message.error('开通周期不可为空')
    return false
  }
  if (!obj.product_id) {
    Message.error('开通产品不可为空')
    return false
  }
  if (!obj.clip_num) {
    Message.error('剪辑次数不可为空')
    return false
  }
  try {
    const res = await api.post('custom/openProduct', obj)
    Message.success(res.message)
    handleChangeTabs(0)
    formVisible.value = false
    resetOpenProductForm()
  } catch (error) {
    console.error('error', error)
    return false
  }
}

const resetOpenProductForm = async () => {
  openProductForm.value = {
    custom_id: id,
    start_time: '',
    cycle: '',
    end_time: '',
    clip_num: '',
    product_id: '',
  }
}

const handleChangeTabs = async (e) => {
  switch (e) {
    case 0:
      OpenLogRef.value.getOpenCustomLog(1)
      break
    case 1:
      AccountManagementRef.value.getAdministratorsList(1)
      break
    case 2:
      OrderRecordRef.value.getCustomOrderList(1)
      break
  }
}

getCustomDetails()
getMenuAllList()
</script>

<template>
  <div class="page">
    <div class="form_body">
      <div class="flex at_c jc_b mb20">
        <div class="form_body_title">基础信息</div>
        <div>
          <a-space>
            <a-button v-if="readonly"
                      @click="readonly = false"
                      type="primary">编辑</a-button>
            <a-button v-if="!readonly"
                      @click="updateCustom"
                      type="outline">保存</a-button>
            <a-button v-if="!readonly"
                      @click="cancelUpdateCustom">取消</a-button>
          </a-space>
        </div>
      </div>

      <a-form>
        <a-row class="grid-demo"
               :gutter="24">
          <a-col :span="8">
            <a-form-item label="客户名称">
              <a-input :readonly="readonly"
                       :style="{width:'400px'}"
                       v-model="customFormInfo.custom_name"
                       placeholder="请输入客户名称"
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="负责人姓名">
              <a-input :readonly="readonly"
                       :style="{width:'400px'}"
                       v-model="customFormInfo.head_name"
                       placeholder="请输入负责人姓名"
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="联系方式">
              <a-input :readonly="readonly"
                       :style="{width:'400px'}"
                       v-model="customFormInfo.mobile"
                       placeholder="请输入联系方式"
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row class="grid-demo"
               :gutter="24">
          <a-col :span="8">
            <a-form-item label="后台链接">
              <a-input :readonly="true"
                       :style="{width:'400px'}"
                       v-model="customInfo.admin_url"
                       placeholder=""
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="H5链接">
              <a-input :readonly="true"
                       :style="{width:'400px'}"
                       v-model="customInfo.h5_url"
                       placeholder=""
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <div class="form_body">
      <div class="flex at_c jc_b mb20">
        <div class="form_body_title">客户状态</div>
        <div>
          <a-button @click="formVisible = true"
                    type="primary">开通</a-button>
        </div>
      </div>

      <a-form>
        <a-row class="grid-demo"
               :gutter="24">
          <a-col :span="7">
            <a-form-item label="客户状态">
              <a-input :readonly="true"
                       :style="{width:'400px'}"
                       v-model="customInfo.custom_statusText"
                       placeholder="请输入生效周期"
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="7">
            <a-form-item label="生效周期">
              <a-input :readonly="true"
                       :style="{width:'400px'}"
                       v-model="customInfo.cycle"
                       placeholder="请输入生效周期"
                       allow-clear></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="状态">
              <a-popconfirm @ok="changeCustomStatus"
                            :content="popconfirmContent"
                            type="warning">
                <a-switch :beforeChange="handleChangeCustomStatus"
                          v-model="customInfo.status"
                          :checked-value="1"
                          :unchecked-value="0" />
              </a-popconfirm>
            </a-form-item>
          </a-col>
          <a-col :span="5">
            <a-form-item label="IP学院">
              <a-popconfirm @ok="changeCustomIpStatus"
                            :content="popconfirmContent"
                            type="warning">
                <a-switch :beforeChange="handleChangeCustomStatus"
                          v-model="customInfo.ip_status"
                          :checked-value="1"
                          :unchecked-value="0" />
              </a-popconfirm>
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </div>

    <a-modal title="开通"
             width="600px"
             :on-before-ok="formSubmit"
             v-model:visible="formVisible">
      <a-form>
        <a-form-item label="开通日期">
          <a-date-picker @blur="getEndTime"
                         v-model="openProductForm.start_time"
                         style="width: 400px;"
                         placeholder="请选择开通日期" />
        </a-form-item>
        <a-form-item label="开通周期">
          <a-input-number @blur="getEndTime"
                          v-model="openProductForm.cycle"
                          :style="{width:'400px'}"
                          placeholder="请输入开通周期"
                          class="input-demo"
                          :min="0" />
        </a-form-item>
        <a-form-item label="截止日期">
          <a-date-picker v-model="openProductForm.end_time"
                         :disabled="true"
                         style="width: 400px;"
                         placeholder=" " />
          <template #extra>
            <div style="color: red">当前日期下已有进行中的订单，将根据订单截止时间顺延周期时间</div>
          </template>
        </a-form-item>
        <a-form-item label="开通产品">
          <a-checkbox-group v-model="openProductForm.product_id">
            <a-checkbox v-for="(item,index) in productList"
                        :key="index"
                        :value="item.id">{{item.title}}</a-checkbox>
          </a-checkbox-group>
        </a-form-item>
        <a-form-item label="剪辑次数">
          <a-input-number v-model="openProductForm.clip_num"
                          :style="{width:'400px'}"
                          placeholder="请输入剪辑次数"
                          class="input-demo"
                          :min="0" />
        </a-form-item>
      </a-form>
    </a-modal>

    <div class="form_body">
      <a-tabs @change="handleChangeTabs"
              :default-active-key="currentActiveKey">
        <a-tab-pane :key="0"
                    title="开通日志">
          <OpenLog ref="OpenLogRef"
                   :customId="id"
                   :productList="productList"></OpenLog>
        </a-tab-pane>
        <a-tab-pane :key="1"
                    title="超管账号管理">
          <AccountManagement ref="AccountManagementRef"
                             :customId="id"></AccountManagement>
        </a-tab-pane>
        <a-tab-pane :key="2"
                    title="订单记录">
          <OrderRecord ref="OrderRecordRef"
                       :customId="id"></OrderRecord>
        </a-tab-pane>
      </a-tabs>
    </div>
  </div>
</template>

<style scoped>
.page {
  height: 100%;
  padding: 20px;
  box-sizing: border-box;
}

.header {
  height: 52px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.form_body {
  box-sizing: border-box;
  padding: 20px 24px;
  background-color: #fff;
  margin-bottom: 20px;
}

.form_body_title {
  font-size: 18px;
  font-weight: bold;
}
</style>